package cur.nature.component.redis.queue;

import cur.nature.framework.core.log.LOG;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
@DependsOn("redisTemplate")
@ConditionalOnProperty( value = {"cur.component.redis.enable"})
public class RedisQueueConfig {
    private static RedisTemplate redisTemplate;
    private static RedisMessageListenerContainer messageContainer;

    public RedisQueueConfig(@Qualifier("redisTemplate") RedisTemplate redisTemplates){
        redisTemplate = redisTemplates;
    }

    public static void produce(String channel, String message) {
        LOG.info("向队列发送消息：" + channel + ", msg: " + message);
        redisTemplate.convertAndSend(channel, message);
    }
    public static void listen(String channel, MessageListener listener) {
        LOG.info("队列开始注册：" + channel);
        messageContainer.addMessageListener(listener, new ChannelTopic(channel));
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
//        container.addMessageListener(redisMessageListenerListener, new ChannelTopic(PubSubRedisQueue.KEY));
        messageContainer = container;
        return container;
    }
}
